from scopt.util.message_types import STRING
from scopt.util import message as msg_util
from . import message


@message(type='context.tenant.find_by_login',
         version='0.1',
         reqd={'login': STRING(required=True)},
         resd={'login': STRING(required=True),
               'tenants': [{'tenant_id': STRING(required=True),
                            'tenant_name': STRING(required=True)}]})
def handle(data_packet, context):
    reqd = msg_util.get_request_data(data_packet)
    login = reqd['login']
    tenants = context.query(['users_tenants', 'tenants'],
                            where=[['users_tenants.login', login]],
                            mapper=_result_mapper)
    return msg_util.ok_response(data_packet, handle, {'login': login,
                                                      'tenants': tenants})


def _result_mapper(result):
    return [{'tenant_id': row['tenants_id'],
             'tenant_name': row['tenants_name']}
            for row in result]
